package com.ziyucoding.springboot.labs.statemachine.service.impl;


import com.ziyucoding.springboot.labs.statemachine.annotation.OrderStateMachineResult;
import com.ziyucoding.springboot.labs.statemachine.common.CommonConstants;
import com.ziyucoding.springboot.labs.statemachine.common.OrderStatus;
import com.ziyucoding.springboot.labs.statemachine.common.OrderStatusChangeEvent;
import com.ziyucoding.springboot.labs.statemachine.domain.Order;
import com.ziyucoding.springboot.labs.statemachine.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 监听状态的变化
 *
 * @author ziyucoding
 * @date 2023-05-29
 **/
@Component("orderStateListener")
@WithStateMachine(name = "orderStateMachine")
@Slf4j
public class OrderStateListenerImpl {

    @Resource
    private OrderMapper orderMapper;

    @OnTransition(source = "WAIT_PAYMENT", target = "WAIT_DELIVER")
    @Transactional(rollbackFor = Exception.class)
    @OrderStateMachineResult(key = CommonConstants.PAY_TRANSITION)
    public void payTransition(Message<OrderStatusChangeEvent> message) {
        Order order = (Order) message.getHeaders().get("order");
        log.info("支付，状态机反馈信息：{}", message.getHeaders().toString());
        // 更新订单
        order.setStatus(OrderStatus.WAIT_DELIVER.getKey());
        orderMapper.updateById(order);
        // TODO 其他业务
//        // 模拟异常
//        if (Objects.equals(order.getName(), "订单A")) {
//            throw new RuntimeException("执行业务异常");
//        }
    }

    @OnTransition(source = "WAIT_DELIVER", target = "WAIT_RECEIVE")
    @Transactional(rollbackFor = Exception.class)
    @OrderStateMachineResult(key = CommonConstants.DELIVER_TRANSITION)
    public void deliverTransition(Message<OrderStatusChangeEvent> message) {
        Order order = (Order) message.getHeaders().get("order");
        log.info("发货，状态机反馈信息：{}", message.getHeaders().toString());
        // 更新订单
        order.setStatus(OrderStatus.WAIT_RECEIVE.getKey());
        orderMapper.updateById(order);
        // TODO 其他业务
    }

    @OnTransition(source = "WAIT_RECEIVE", target = "FINISH")
    @Transactional(rollbackFor = Exception.class)
    @OrderStateMachineResult(key = CommonConstants.RECEIVE_TRANSITION)
    public void receiveTransition(Message<OrderStatusChangeEvent> message) {
        Order order = (Order) message.getHeaders().get("order");
        log.info("确认收货，状态机反馈信息：{}", message.getHeaders().toString());
        // 更新订单
        order.setStatus(OrderStatus.FINISH.getKey());
        orderMapper.updateById(order);
        // TODO 其他业务
    }
}
